//
//  DZApplePayHelper.m
#import "DZApplePayHelper.h"
#import <StoreKit/StoreKit.h>
@interface DZApplePayHelper ()<SKProductsRequestDelegate,SKPaymentTransactionObserver>
@property (nonatomic, strong) SKProductsRequest *request;
@property (nonatomic, copy) NSString *payOrderNo;
@property (nonatomic, copy) NSString *productId;
@property (nonatomic, strong) SKPaymentTransaction* transaction;
@end

@implementation DZApplePayHelper
+ (instancetype)defaultManager{
    static DZApplePayHelper* instance = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [DZApplePayHelper new];
    });
    return instance;
}
- (instancetype)init{
    self= [super init];
    if(self) {
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
    }
    return self;
}
- (void)removeTransaction{
    if (self.transaction) {
        [[SKPaymentQueue defaultQueue] finishTransaction: self.transaction];
    }
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}
//开始苹果支付
- (void)beginApplePay:(NSString *)productId{
    DZWeakSelf
    if (productId.length > 0) {
        self.productId = productId;
        //添加支付服务
        if (self.transaction) {
            [[SKPaymentQueue defaultQueue] finishTransaction: self.transaction];
        }
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        if([SKPaymentQueue canMakePayments]){
            //去苹果服务器请求商品
            [SVProgressHUD showWithStatus:@"正在支付，请勿中断"];
            [weakSelf requestProductData:productId];
        }
    }
}
//去苹果服务器请求商品
- (void)requestProductData:(NSString *)type{
    NSArray *product = [[NSArray alloc] initWithObjects:type,nil];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}
#pragma mark - SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response{
    NSArray *product = response.products;
    if(product && product.count > 0){
        for (int i = 0; i < product.count; i++) {
            SKProduct *pro = product[i];
            if ([pro.productIdentifier isEqualToString:self.productId]) {
                SKPayment *payment = [SKPayment paymentWithProduct:pro];
                [[SKPaymentQueue defaultQueue] addPayment:payment];
            }
        }
    }else{
        [SVProgressHUD dismiss];
        [DzAlertHelper showMessage:@"苹果支付没有找到对应的产品"];
    }
}
//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    dispatch_async(dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
        [DzAlertHelper showMessage:@"支付失败"];
    });
}
- (BOOL)paymentQueue:(SKPaymentQueue *)queue shouldAddStorePayment:(SKPayment *)payment forProduct:(SKProduct *)product {
    // Add your implementation here
    // Return YES if the payment should be added to the payment queue, or NO if not
    return YES;
}
#pragma mark - SKPaymentTransactionObserver
/** 监听购买结果 */
- (void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray *)transactions{
    DZWeakSelf
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{//交易完成
                //交易结束，当交易结束后还要去appstore上验证支付信息
                [weakSelf completeTransaction:tran];
            }
            break;
            case SKPaymentTransactionStatePurchasing:{//商品添加进列表
            }
            break;
            case SKPaymentTransactionStateRestored:{//已经购买过该商品
                [SVProgressHUD dismiss];
                [queue finishTransaction:tran];
                if(weakSelf.ApplePayRepeatBuyVipBlock){
                    weakSelf.ApplePayRepeatBuyVipBlock();
                }
            }
            break;
            case SKPaymentTransactionStateFailed:{//购买失败
                [weakSelf finshTransaction:tran];
            }
            break;
            default:
                break;
        }
    }
}
// Sent when transactions are removed from the queue (via finishTransaction:).
- (void)paymentQueue:(SKPaymentQueue*)queue removedTransactions:(NSArray *)transactions{
    NSLog(@"---removedTransactions");
}
// Sent when an error is encountered while adding transactions from the user's purchase history back to the queue.
- (void)paymentQueue:(SKPaymentQueue*)queue restoreCompletedTransactionsFailedWithError:(NSError*)error{
    NSLog(@"restoreCompletedTransactionsFailedWithError");
}
// Sent when all transactions from the user's purchase history have successfully been added back to the queue.
- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue*)queue{
    NSLog(@"paymentQueueRestoreCompletedTransactionsFinished");
}
// Sent when the download state has changed.

- (void)paymentQueue:(SKPaymentQueue*)queue updatedDownloads:(NSArray *)downloads{
    NSLog(@"updatedDownloads");
}
#pragma mark 验证购买
- (void)completeTransaction:(SKPaymentTransaction*)transaction{
    self.transaction = transaction;
    /// 这里的URL测试环境下为沙盒url，上线版本中应为苹果后台的URL
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    /// 转化为base64字符串
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    // 客户端请求苹果接口进行票据校验（该操作由服务器来验证）
    [self localReceiptVerifyingWithUrl:DZSandboxUrl AndReceipt:receiptString AndTransaction:transaction];
    // 监听购买结果，当失败和成功时代码中要调用如下代码:
    // 该方法通知苹果支付队列该交易已完成，不然就会已发起相同 ID 的商品购买就会有此项目将免费恢复的提示。
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)finshTransaction:(SKPaymentTransaction*)transaction{
    self.transaction = transaction;
    [SVProgressHUD dismiss];
//    [MBProgressHUD hideHUDForView:[UIApplication sharedApplication].keyWindow.rootViewController.view animated:YES];
    //结束交易
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
/// 请求苹果接口进行票据校验
- (void)localReceiptVerifyingWithUrl:(NSString *)requestUrl AndReceipt:(NSString *)receiptStr AndTransaction:(SKPaymentTransaction *)transaction
{
    DZWeakSelf
    NSDictionary *requestContents = @{@"receipt-data": receiptStr,@"password":DZProductKey,@"exclude-old-transactions":@(true)};
    NSError *error;
    // 转换为 JSON 格式
    NSData *requestData = [NSJSONSerialization dataWithJSONObject:requestContents options:0 error:&error];
    NSString *verifyUrlString = requestUrl;
    NSMutableURLRequest *storeRequest = [NSMutableURLRequest requestWithURL:[[NSURL alloc] initWithString:verifyUrlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0f];
    [storeRequest setHTTPMethod:@"POST"];
    [storeRequest setHTTPBody:requestData];
    // 在后台对列中提交验证请求，并获得官方的验证JSON结果
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:storeRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        if (error) {
            NSLog(@"链接失败");
            [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
        } else {
            NSError *error;
            NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
            if (!jsonResponse) {
                NSLog(@"验证失败");
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    if(weakSelf.ApplePayBuyVipBlock){
                        weakSelf.ApplePayBuyVipBlock();
                    }
                });
            }
            NSLog(@"验证成功");
        }
    }];
    [task resume];
}
-(void)dealloc{
    [[SKPaymentQueue defaultQueue] finishTransaction:self.transaction];
}
@end




